package com.madou.dbtool.redis.panel;

import com.madou.common.annotation.HideClass;
import com.madou.dbtool.common.icon.AllIcons;
import com.madou.dbtool.event.DBEvent;
import com.madou.dbtool.event.EventPanel;
import com.madou.dbtool.language.enums.ContentTypeEnum;
import com.madou.dbtool.redis.event.OpenRedisMonitorEvent;
import com.madou.dbtool.redis.manager.RedisNodeInfo;
import com.madou.dbtool.redis.manager.RedisSourceManager;
import com.madou.dbtool.redis.panel.callback.JedisMonitorCallback;
import com.madou.dbtool.redis.terminal.RedisTerminal;
import com.madou.dbtool.ui.content.TitleNo;

import javax.swing.*;

/**
 * redis的终端监控面板
 * @author miukoo
 */
@HideClass
public class RedisMonitorEventPanel extends RedisTerminal implements EventPanel, TitleNo {

    String title;
    // 监听结果的线程
    Thread monitor;
    int dbIndex;

    public RedisMonitorEventPanel() {
        super(ContentTypeEnum.REDIS);
    }

    public static DBEvent bingEvent() {
        return OpenRedisMonitorEvent.NAME;
    }

    @Override
    public void actionEvent(DBEvent event) {
        if(event instanceof OpenRedisMonitorEvent){
            OpenRedisMonitorEvent e = (OpenRedisMonitorEvent)event;
            RedisSourceManager clone = e.getRedisSourceManager().cloneDirect();
            this.setRedisSourceManager(clone);
            this.setCacheCommand(false);
            this.dbIndex = e.getDbIndex();
            this.title = String.format("Monitor-%s:%d",e.getRedisNodeInfo().getIp(),e.getRedisNodeInfo().getPort());
            this.setTitle(title);
            this.title = this.getTitle(title);
        }
    }

    @Override
    public String title() {
        return title;
    }


    /**
     * 初始化
     * @return
     */
    @Override
    public void init(){
        if(monitor==null) {
            monitor = new Thread(new JedisMonitorCallback(this));
            monitor.start();
        }
    }

    /**
     * 是否可以滚动
     * @return
     */
    @Override
    public boolean canScroll(){
        return true;
    }

    @Override
    public Icon icon(){
        return AllIcons.Common.QUERY_LOG;
    }

    /**
     * 关闭按钮的回调函数
     * @return
     */
    @Override
    public void onClose(){
        this.clearTitle(title);
        if(monitor==null) {
            monitor.stop();
        }
        this.getRedisSourceManager().close();
    }

    @Override
    public int getDBIndex() {
        return dbIndex;
    }
}
